package com.xyz.mycamera

import android.Manifest
import android.os.Bundle
import android.view.WindowManager
import android.widget.ImageView
import androidx.activity.ComponentActivity
import androidx.core.view.isVisible
import com.blankj.utilcode.util.PermissionUtils
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.xyz.mycamera.databinding.ActivityMainBinding
import com.xyz.mycamera.picture.PictureSelectorUtils

class MainActivity : ComponentActivity() {

    private val permission by lazy {
        arrayOf(
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.CAMERA
        )
    }
    private val binding by lazy {
        ActivityMainBinding.inflate(layoutInflater)
    }
    /*private val mCameraProxy by lazy {
        binding.surfaceView.cameraProxy
    }*/

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        setContentView(binding.root)
        ImmersionBar.with(this)
            .fullScreen(true)
            .hideBar(BarHide.FLAG_HIDE_BAR)
            .init()

        if (PermissionUtils.isGranted(*permission)) {
            binding.surfaceView.switchCamera()
//            mCameraProxy.startCamera()
            binding.surfaceView.startCamera()
        } else {
            PermissionUtils.permission(
                *permission
            ).callback { isAllGranted, _, _, _ ->
                if (isAllGranted) {
//                    mCameraProxy.startCamera()
                    binding.surfaceView.startCamera()
                }
            }.request()
        }
        binding.ivLeft.setOnClickListener {
            openPicture(binding.ivLeft)
        }
        binding.ivRight.setOnClickListener {
            openPicture(binding.ivRight)
        }
        binding.btnChange.setOnClickListener {
//            mCameraProxy.switchCamera()
            binding.surfaceView.switchCamera()
        }
        binding.btnStart.setOnClickListener {
            binding.btnStart.isVisible = false
            binding.btnChange.isVisible = false
            binding.etContent.isEnabled = false
        }
    }

    private fun openPicture(imageView: ImageView) {
        PictureSelectorUtils.openGallery(
            this, arrayListOf(), 1, null
        ) { b, list ->
            if (list.size > 0) {
                GlideManager.loadUrl(list[0].path, imageView)
            }
        }
    }

    override fun onResume() {
        super.onResume()
        binding.surfaceView.startCamera()
    }

    override fun onDestroy() {
        super.onDestroy()
//        mCameraProxy.stopPreview()
        binding.surfaceView.onDestroy()
    }
}
